﻿using SHZY.Common.Core.Manager;
using SHZY.Common.Core.Security;
using SHZY.ClayObject;
using SHZY.Common.Configuration;
using SHZY.Common.Models.NPOI;
using SHZY.DataEncryption;
using SHZY.Common.Enum;
using SHZY.Common.Extension;
using SHZY.Common.Filter;
using SHZY.Common.Models;
using SHZY.Common.Security;
using SHZY.DependencyInjection;
using SHZY.DynamicApiController;
using SHZY.FriendlyException;
using SHZY.Systems.Entitys.Permission;
using SHZY.Systems.Entitys.System;
using SHZY.BaseData.Entitys.Dto.QmsBaseInspectionrolemain;
using SHZY.BaseData.Entitys;
using SHZY.BaseData.Interfaces;
using Mapster;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using Microsoft.AspNetCore.Http;
using SHZY.Common.Core.Manager.Files;
using SHZY.Common.Helper;
using Org.BouncyCastle.Crypto;
using SHZY.BaseData.Entitys.Dto.QmsBaseInspectionrole;

namespace SHZY.BaseData;

/// <summary>
/// 业务实现：跳检规则.
/// </summary>
[ApiDescriptionSettings(Tag = "BaseData", Name = "Inspectionrole", Order = 200)]
[Route("api/BaseData/[controller]")]
public class QmsBaseInspectionrolemainService : IQmsBaseInspectionrolemainService, IDynamicApiController, ITransient
{
    /// <summary>
    /// 服务基础仓储.
    /// </summary>
    private readonly ISqlSugarRepository<QmsBaseInspectionrolemainEntity> _repository;

    /// <summary>
    /// 多租户事务.
    /// </summary>
    private readonly ITenant _db;

    /// <summary>
    /// 用户管理.
    /// </summary>
    private readonly IUserManager _userManager;

    /// <summary>
    /// 文件管理.
    /// </summary>
    private readonly IFileManager _fileManager;

    /// <summary>
    /// 初始化一个<see cref="QmsBaseInspectionrolemainService"/>类型的新实例.
    /// </summary>
    public QmsBaseInspectionrolemainService(
        ISqlSugarRepository<QmsBaseInspectionrolemainEntity> qmsBaseInspectionrolemainRepository,
        ISqlSugarClient context,
        IFileManager fileManager,
        IUserManager userManager)
    {
        _repository = qmsBaseInspectionrolemainRepository;
        _db = context.AsTenant();
        _userManager = userManager;
        _fileManager = fileManager;
    }

    /// <summary>
    /// 获取跳检规则.
    /// </summary>
    /// <param name="id">主键值.</param>
    /// <returns></returns>
    [HttpGet("{id}")]
    public async Task<dynamic> GetInfo(string id)
    {
        var inspectionrolemainInfoOutput = (await _repository.FirstOrDefaultAsync(x => x.Id == id)).Adapt<QmsBaseInspectionrolemainInfoOutput>();
        var inspectionroleUpInput = await _repository.Context.Queryable<QmsBaseInspectionroleEntity>().Where(x => x.MainId == id&& x.DeleteMark == null).Select(a => new QmsBaseInspectionroleInfoOutput
        {

            stage = a.Stage,
            stageDesc = a.StageDesc,
            judeCondition = a.JudeCondition,
            continuityDay = a.ContinuityDay,
            inspLot = a.InspLot,
            keyWord = a.KeyWord,
            okStageNo = a.OkStageNo,
            rejectNun = a.RejectNun,
            ngStageNo = a.NgStageNo,
            isDefault = a.IsDefault.ToString(),
            isExempt = a.IsExempt.ToString(),
            enabledMark = a.EnabledMark
        }).ToListAsync();
        inspectionrolemainInfoOutput.children = inspectionroleUpInput;
        return inspectionrolemainInfoOutput;
    }

    /// <summary>
    /// 获取所有跳检规则.
    /// </summary>
    /// <returns></returns>
    [HttpGet("All")]
    public async Task<dynamic> GetListAll()
    {
        var data = await _repository.AsQueryable().Where(x => x.DeleteMark == null && x.EnabledMark == 1)
            .OrderBy(x => x.Code).ToListAsync();
        return new { list = data.Adapt<List<QmsBaseInspectionrolemainInfoOutput>>() };

    }

    /// <summary>
    /// 获取跳检规则列表.
    /// </summary>
    /// <param name="input">请求参数.</param>
    /// <returns></returns>
    [HttpGet("")]
    public async Task<dynamic> GetList([FromQuery] QmsBaseInspectionrolemainListQueryInput input)
    {
        var queryable = _repository.Context.Queryable<QmsBaseInspectionrolemainEntity>()
            .WhereIF(!string.IsNullOrEmpty(input.code), it => it.Code.Contains(input.code))
            .WhereIF(!string.IsNullOrEmpty(input.desc), it => it.Desc.Contains(input.desc))
            .WhereIF(!string.IsNullOrEmpty(input.keyword), it => it.Code.Contains(input.keyword) || it.Desc.Contains(input.keyword))
            .Where(a => a.DeleteMark == null)
            .Select(it => new QmsBaseInspectionrolemainListOutput
            {
                id = it.Id,
                code = it.Code,
                desc = it.Desc,
                startDate = Convert.ToDateTime(it.StartDate).ToString("yyyy-MM-dd hh:mm:ss"),
                endDate = Convert.ToDateTime(it.EndDate).ToString("yyyy-MM-dd hh:mm:ss"),
                enabledMark = SqlFunc.IIF(it.EnabledMark == 0, "停用", "正常"),
            }).MergeTable();
            //.OrderByIF(string.IsNullOrEmpty(input.sidx), it => it.Id);

        if (!string.IsNullOrEmpty(input.sidx))
        {
            if (input.sidx == "desc")
            {
                queryable.OrderBy("[desc]" + " " + input.sort);
            }
            else
            {
                queryable.OrderBy(input.sidx + " " + input.sort);
            }
        }

        var sql = queryable.ToSql();

        var data = await queryable.ToPagedListAsync(input.currentPage, input.pageSize);
        return PageResult<QmsBaseInspectionrolemainListOutput>.SqlSugarPageResult(data);
    }

    /// <summary>
    /// 提交保存跳检规则.
    /// </summary>
    /// <param name="input">参数.</param>
    /// <returns></returns>
    [HttpPost("")]
    public async Task Submit([FromBody] QmsBaseInspectionrolemainUpInput input)
    {
        try
        {
            // 开启事务
            _db.BeginTran();
            input.code = input.code.Trim();
            input.desc = input.desc.Trim();

            // 处理跳检规则
            var entity = input.Adapt<QmsBaseInspectionrolemainEntity>();
            if (string.IsNullOrEmpty(input.id))
            {
                if (await _repository.AnyAsync(x => (x.Code == input.code || x.Desc == input.desc) && x.DeleteMark == null))
                    throw Oops.Oh(ErrorCode.COM1004);
                var isOk = await _repository.Context.Insertable(entity).IgnoreColumns(ignoreNullColumn: true).CallEntityMethod(m => m.Creator()).ExecuteCommandAsync();
                if (isOk < 1)
                    throw Oops.Oh(ErrorCode.COM1000);

            }
            else
            {
                if (await _repository.AnyAsync(x => (x.Code == input.code || x.Desc == input.desc) && x.DeleteMark == null && x.Id != input.id))
                    throw Oops.Oh(ErrorCode.COM1004);
                var isOk = await _repository.Context.Updateable(entity).IgnoreColumns(ignoreAllNullColumns: true).CallEntityMethod(m => m.LastModify()).ExecuteCommandHasChangeAsync();
                if (!isOk)
                    throw Oops.Oh(ErrorCode.COM1001);

                // 如果是编辑，先删除明细，再新增
                isOk = await _repository.Context.Updateable<QmsBaseInspectionroleEntity>().SetColumns(it => new QmsBaseInspectionroleEntity()
                {
                    DeleteTime = DateTime.Now,
                    DeleteMark = 1,
                    DeleteUserId = _userManager.UserId
                }).Where(x => x.MainId == entity.Id).ExecuteCommandHasChangeAsync();
                if (!isOk)
                    throw Oops.Oh(ErrorCode.COM1002);
            }

            // 处理跳检规则明细
            foreach (var item in input.children)
            {
                item.mainId = entity.Id;
                var inspectionroleEntity = item.Adapt<QmsBaseInspectionroleEntity>();
                if (await _repository.Context.Queryable<QmsBaseInspectionroleEntity>().AnyAsync(x => x.MainId == item.mainId && (x.Stage == item.stage || x.StageDesc == item.stageDesc) && x.DeleteMark == null))
                    throw Oops.Oh(ErrorCode.COM1004);
                var isOk = await _repository.Context.Insertable(inspectionroleEntity).IgnoreColumns(ignoreNullColumn: true).CallEntityMethod(m => m.Creator()).ExecuteCommandAsync();
                if (isOk < 1)
                    throw Oops.Oh(ErrorCode.COM1000);
            }

            // 关闭事务
            _db.CommitTran();

        }
        catch (Exception ex)
        {
            // 回滚事务
            _db.RollbackTran();
            throw Oops.Oh(ex.Message);
        }
    }

    /// <summary>
    /// 获取跳检规则无分页列表.
    /// </summary>
    /// <param name="input">请求参数.</param>
    /// <returns></returns>
    private async Task<dynamic> GetNoPagingList([FromQuery] QmsBaseInspectionrolemainListQueryInput input)
    {
        var queryable = _repository.Context.Queryable<QmsBaseInspectionrolemainEntity, QmsBaseInspectionroleEntity>((a,b)=> new JoinQueryInfos(JoinType.Left, a.Id == b.MainId&& b.DeleteMark==null))
            .WhereIF(!string.IsNullOrEmpty(input.code), a => a.Code.Contains(input.code))
            .WhereIF(!string.IsNullOrEmpty(input.desc), a => a.Desc.Contains(input.desc))
            .WhereIF(!string.IsNullOrEmpty(input.keyword), a => a.Code.Contains(input.keyword) || a.Desc.Contains(input.keyword))
            .Where(a => a.DeleteMark == null)
            .OrderByIF(string.IsNullOrEmpty(input.sidx), a => a.Id);
        if (!string.IsNullOrEmpty(input.sidx))
        {
            queryable.OrderBy(input.sidx + " " + input.sort);
        }
        if (input.dataType == 0)
        {
            return (await queryable.Select((a, b) => new QmsBaseInspectionrolemainListOutput
            {
                id = a.Id,
                code = a.Code,
                desc = a.Desc,
                startDate = Convert.ToDateTime(a.StartDate).ToString("yyyy-MM-dd hh:mm:ss"),
                endDate = Convert.ToDateTime(a.EndDate).ToString("yyyy-MM-dd hh:mm:ss"),
                enabledMark = SqlFunc.IIF(a.EnabledMark == 0, "停用", "正常"),
                stage = b.Stage,
                stageDesc = b.StageDesc,
                judeCondition = b.JudeCondition,
                continuityDay = b.ContinuityDay,
                inspLot = b.InspLot,
                keyWord = SqlFunc.IIF(b.KeyWord == "and", "并且", "或者"),
                okStageNo = b.OkStageNo,
                rejectNun = b.RejectNun,
                ngStageNo = b.NgStageNo,
                isDefault = SqlFunc.IIF(b.IsDefault == 0, "否", "是"),
                isExempt = SqlFunc.IIF(b.IsExempt == 0, "否", "是"),
                enabledMark1 = SqlFunc.IIF(b.EnabledMark == 0, "停用", "正常")
            }).ToPagedListAsync(input.currentPage, input.pageSize)).list;
        }
        else
        {
            return await queryable.Select((a, b) => new QmsBaseInspectionrolemainListOutput
            {
                id = a.Id,
                code = a.Code,
                desc = a.Desc,
                startDate = Convert.ToDateTime(a.StartDate).ToString("yyyy-MM-dd hh:mm:ss"),
                endDate = Convert.ToDateTime(a.EndDate).ToString("yyyy-MM-dd hh:mm:ss"),
                enabledMark = SqlFunc.IIF(a.EnabledMark == 0, "停用", "正常"),
                stage = b.Stage,
                stageDesc = b.StageDesc,
                judeCondition = b.JudeCondition,
                continuityDay = b.ContinuityDay,
                inspLot = b.InspLot,
                keyWord = SqlFunc.IIF(b.KeyWord == "and", "并且", "或者"),
                okStageNo = b.OkStageNo,
                rejectNun = b.RejectNun,
                ngStageNo = b.NgStageNo,
                isDefault = SqlFunc.IIF(b.IsDefault == 0, "否", "是"),
                isExempt = SqlFunc.IIF(b.IsExempt == 0, "否", "是"),
                enabledMark1 = SqlFunc.IIF(b.EnabledMark == 0, "停用", "正常")
            }).ToListAsync();
        }
    }

    /// <summary>
    /// 导出跳检规则.
    /// </summary>
    /// <param name="input">请求参数.</param>
    /// <returns></returns>
    [HttpGet("Actions/Export")]
    public async Task<dynamic> Export([FromQuery] QmsBaseInspectionrolemainListQueryInput input)
    {
        var exportData = await GetNoPagingList(input);
        List<ParamsModel> paramList = "[{\"value\":\"规则编码\",\"field\":\"code\"},{\"value\":\"规则描述\",\"field\":\"desc\"},{\"value\":\"有效开始时间\",\"field\":\"startDate\"},{\"value\":\"有效结束时间\",\"field\":\"endDate\"},{\"value\":\"有效标志\",\"field\":\"enabledMark\"},{\"value\":\"阶段\",\"field\":\"stage\"},{\"value\":\"阶段描述\",\"field\":\"stageDesc\"},{\"value\":\"条件\",\"field\":\"judeCondition\"},{\"value\":\"连续天数\",\"field\":\"continuityDay\"},{\"value\":\"与批次关系\",\"field\":\"keyWord\"},{\"value\":\"合格数\",\"field\":\"inspLot\"},{\"value\":\"新阶段\",\"field\":\"okStageNo\"},{\"value\":\"拒绝\",\"field\":\"rejectNun\"},{\"value\":\"NG新阶段\",\"field\":\"ngStageNo\"},{\"value\":\"初始阶段\",\"field\":\"isDefault\"},{\"value\":\"免检\",\"field\":\"isExempt\"},{\"value\":\"有效标志（明细）\",\"field\":\"enabledMark1\"},]".ToList<ParamsModel>();
        ExcelConfig excelconfig = new ExcelConfig();
        excelconfig.FileName = "跳检规则.xls";
        excelconfig.HeadFont = "微软雅黑";
        excelconfig.HeadPoint = 10;
        excelconfig.IsAllSizeColumn = true;
        excelconfig.ForeColor = System.Drawing.Color.Green;
        excelconfig.Background= System.Drawing.Color.Green;
        excelconfig.ColumnModel = new List<ExcelColumnModel>();
        foreach (var item in input.selectKey.Split(',').ToList())
        {
            var isExist = paramList.Find(p => p.field == item);
            if (isExist != null)
                excelconfig.ColumnModel.Add(new ExcelColumnModel() { Column = isExist.field, ExcelColumn = isExist.value ,Width=25});
        }

        var addPath = FileVariable.TemporaryFilePath + excelconfig.FileName;
        ExcelExportHelper<QmsBaseInspectionrolemainListOutput>.Export(exportData, excelconfig, addPath);
        var fileName = _userManager.UserId + "|" + addPath + "|xls";
        return new
        {
            name = excelconfig.FileName,
            url = "/api/File/Download?encryption=" + DESCEncryption.Encrypt(fileName, "SHZY")
        };
    }

    /// <summary>
    /// 批量删除跳检规则.
    /// </summary>
    /// <param name="ids">主键数组.</param>
    /// <returns></returns>
    [HttpPost("batchRemove")]
    public async Task BatchRemove([FromBody] List<string> ids)
    {
        var entitys = await _repository.Context.Queryable<QmsBaseInspectionrolemainEntity>().In(it => it.Id, ids).ToListAsync();
        if (entitys.Count > 0)
        {
            try
            {
                // 开启事务
                _db.BeginTran();
                var isOk = await _repository.Context.Updateable<QmsBaseInspectionrolemainEntity>().SetColumns(it => new QmsBaseInspectionrolemainEntity()
                {
                    DeleteTime = DateTime.Now,
                    DeleteMark = 1,
                    DeleteUserId = _userManager.UserId
                }).Where(it => ids.Contains(it.Id)).ExecuteCommandHasChangeAsync();

                isOk = await _repository.Context.Updateable<QmsBaseInspectionroleEntity>().SetColumns(it => new QmsBaseInspectionroleEntity()
                {
                    DeleteTime = DateTime.Now,
                    DeleteMark = 1,
                    DeleteUserId = _userManager.UserId
                }).Where(it => ids.Contains(it.MainId)).ExecuteCommandHasChangeAsync();

                // 关闭事务
                _db.CommitTran();
            }
            catch (Exception)
            {
                // 回滚事务
                _db.RollbackTran();

                throw Oops.Oh(ErrorCode.COM1002);
            }
        }
    }

    /// <summary>
    /// 更新跳检规则.
    /// </summary>
    /// <param name="id">主键值.</param>
    /// <param name="input">参数.</param>
    /// <returns></returns>
    [HttpPut("{id}")]
    public async Task Update(string id, [FromBody] QmsBaseInspectionrolemainUpInput input)
    {
        if (await _repository.AnyAsync(x => (x.Code == input.code || x.Desc == input.desc) && x.DeleteMark == null && x.Id != input.id))
            throw Oops.Oh(ErrorCode.COM1004);
        var entity = input.Adapt<QmsBaseInspectionrolemainEntity>();
        var isOk = await _repository.Context.Updateable(entity).IgnoreColumns(ignoreAllNullColumns: true).CallEntityMethod(m => m.LastModify()).ExecuteCommandHasChangeAsync();
        if (!isOk)
            throw Oops.Oh(ErrorCode.COM1001);
    }

    /// <summary>
    /// 删除跳检规则.
    /// </summary>
    /// <returns></returns>
    [HttpDelete("{id}")]
    public async Task Delete(string id)
    {
        try
        {
            // 开启事务
            _db.BeginTran();

            var isOk = await _repository.Context.Updateable<QmsBaseInspectionrolemainEntity>().SetColumns(it => new QmsBaseInspectionrolemainEntity()
            {
                DeleteTime = DateTime.Now,
                DeleteMark = 1,
                DeleteUserId = _userManager.UserId
            }).Where(x => x.Id == id).ExecuteCommandHasChangeAsync();
            if (!isOk)
                throw Oops.Oh(ErrorCode.COM1002);
            isOk = await _repository.Context.Updateable<QmsBaseInspectionroleEntity>().SetColumns(it => new QmsBaseInspectionroleEntity()
            {
                DeleteTime = DateTime.Now,
                DeleteMark = 1,
                DeleteUserId = _userManager.UserId
            }).Where(x => x.MainId == id).ExecuteCommandHasChangeAsync();
            if (!isOk)
                throw Oops.Oh(ErrorCode.COM1002);

            // 关闭事务
            _db.CommitTran();
        }
        catch (Exception)
        {
            // 回滚事务
            _db.RollbackTran();

            throw Oops.Oh(ErrorCode.COM1002);
        }
    }

    /// <summary>
    /// 上传文件.
    /// </summary>
    /// <param name="file"></param>
    /// <returns></returns>
    [HttpPost("Uploader")]
    public async Task<dynamic> Uploader(IFormFile file)
    {
        try
        {
            var _filePath = _fileManager.GetPathByType(string.Empty);
            var _fileName = DateTime.Now.ToString("yyyyMMdd") + "_" + SnowflakeIdHelper.NextId() + Path.GetExtension(file.FileName);
            var stream = file.OpenReadStream();
            await _fileManager.UploadFileByType(stream, _filePath, _fileName);
            return new { name = _fileName, url = string.Format("/api/File/Image/{0}/{1}", string.Empty, _fileName) };

        }
        catch (Exception ex)
        {
            throw Oops.Oh(ErrorCode.D8001);
        }
    }

    /// <summary>
    /// 导入数据.
    /// </summary>
    /// <param name="input">请求参数</param>
    /// <returns></returns>
    [HttpPost("ImportData")]
    public async Task<dynamic> ImportData([FromBody] QmsBaseInspectionrolemainImportDataInput input)
    {
        var output = new QmsBaseInspectionrolemainImportDataOutput();
        string id = ""; // 规则id
        string code = ""; // 规则编码
        Dictionary<string,string> inspectionroleMainList = new Dictionary<string, string>();   // 存放跳检主表编码
        // 开启事务
        _db.BeginTran();
        foreach (var item in input.list)
        {
            try
            {
                string exceptionMsg = "";

                #region 数据校验
                if (string.IsNullOrWhiteSpace(item.code))
                {
                    exceptionMsg += "规则编码不能为空；";
                }
                else
                {
                    if (item.code?.Length > 100)
                    {
                        exceptionMsg += "规则编码超出规定长度；";
                    }
                    else
                    {
                        inspectionroleMainList[item.code] = item.id;
                    }
                }
                if (string.IsNullOrWhiteSpace(item.desc))
                {
                    exceptionMsg += "规则描述不能为空；";
                }
                else
                {
                    if (item.desc?.Length > 100)
                    {
                        exceptionMsg += "规则编码超出规定长度；";
                    }
                }
                if (string.IsNullOrWhiteSpace(item.startDate) || string.IsNullOrWhiteSpace(item.endDate))
                {
                    exceptionMsg += "时间不能为空；";
                }
                if (string.IsNullOrWhiteSpace(item.stage))
                {
                    exceptionMsg += "阶段不能为空；";
                }
                if (string.IsNullOrWhiteSpace(item.stageDesc))
                {
                    exceptionMsg += "阶段描述不能为空；";
                }
                if (string.IsNullOrWhiteSpace(item.judeCondition))
                {
                    exceptionMsg += "条件不能为空；";
                }
                if (item.continuityDay == null)
                {
                    exceptionMsg += "时间不能为空；";
                }
                else
                {
                    if (item.continuityDay.ParseToInt() == 0)
                    {
                        exceptionMsg += "连续天数请填写数字；";
                    }
                }
                if (string.IsNullOrWhiteSpace(item.keyWord))
                {
                    exceptionMsg += "与批次关系不能为空；";
                }
                if (item.inspLot.IsNullOrEmpty())
                {
                    exceptionMsg += "合格数不能为空；";
                }
                else
                {
                    if (item.inspLot.ParseToInt() == 0)
                    {
                        exceptionMsg += "合格数请填写数字；";
                    }
                }
                if (string.IsNullOrWhiteSpace(item.okStageNo))
                {
                    exceptionMsg += "新阶段不能为空；";
                }
                if (item.rejectNun.IsNullOrEmpty())
                {
                    exceptionMsg += "拒绝不能为空；";
                }
                else
                {
                    if (item.rejectNun.ParseToDecimal() == 0)
                    {
                        exceptionMsg += "拒绝请填写数字；";
                    }
                }
                if (string.IsNullOrWhiteSpace(item.ngStageNo))
                {
                    exceptionMsg += "NG新阶段不能为空；";
                }
                if (string.IsNullOrWhiteSpace(item.isDefault))
                {
                    exceptionMsg += "初始阶段不能为空；";
                }
                if (string.IsNullOrWhiteSpace(item.isExempt))
                {
                    exceptionMsg += "免检不能为空；";
                }
                #endregion

                if (!exceptionMsg.IsNullOrWhiteSpace()) throw Oops.Oh(exceptionMsg);

                if (inspectionroleMainList[item.code].IsNullOrWhiteSpace())
                {
                    if (await _repository.AnyAsync(x => x.Code == item.code && x.DeleteMark == null))
                        throw Oops.Oh("已存在同编码数据");
                    var inspectionrolemainEntity = item.Adapt<QmsBaseInspectionrolemainEntity>();
                    var isOk = await _repository.Context.Insertable(inspectionrolemainEntity).IgnoreColumns(ignoreNullColumn: true).CallEntityMethod(m => m.Creator()).ExecuteCommandAsync();
                    if (isOk < 1)
                        throw Oops.Oh(ErrorCode.COM1000);
                    id = inspectionrolemainEntity.Id;
                }
                else
                {
                    var inspectionroleEntity = item.Adapt<QmsBaseInspectionroleEntity>();
                    inspectionroleEntity.MainId = id;
                    if (await _repository.Context.Queryable<QmsBaseInspectionroleEntity>().AnyAsync(x => x.MainId == id && x.Stage == item.stage && x.DeleteMark == null))
                        throw Oops.Oh(ErrorCode.COM1004);
                    var isOk1 = await _repository.Context.Insertable(inspectionroleEntity).IgnoreColumns(ignoreNullColumn: true).CallEntityMethod(m => m.Creator()).ExecuteCommandAsync();
                    if (isOk1 < 1)
                    {
                        throw Oops.Oh(ErrorCode.COM1000);
                    }
                    else
                    {
                        output.snum++;
                    }
                }

                //if (!item.code.Equals(code))
                //{
                //    if (await _repository.AnyAsync(x => x.Code == item.code && x.DeleteMark == null))
                //        throw Oops.Oh(ErrorCode.COM1004);
                //    var inspectionrolemainEntity = item.Adapt<QmsBaseInspectionrolemainEntity>();
                //    var isOk = await _repository.Context.Insertable(inspectionrolemainEntity).IgnoreColumns(ignoreNullColumn: true).CallEntityMethod(m => m.Creator()).ExecuteCommandAsync();
                //    if (isOk < 1)
                //        throw Oops.Oh(ErrorCode.COM1000);
                //    id = inspectionrolemainEntity.Id;
                //}

                //var inspectionroleEntity = item.Adapt<QmsBaseInspectionroleEntity>();
                //inspectionroleEntity.MainId = id;
                //if (await _repository.Context.Queryable<QmsBaseInspectionroleEntity>().AnyAsync(x => x.MainId == id && x.Stage == item.stage && x.DeleteMark == null))
                //    throw Oops.Oh(ErrorCode.COM1004);
                //var isOk1 = await _repository.Context.Insertable(inspectionroleEntity).IgnoreColumns(ignoreNullColumn: true).CallEntityMethod(m => m.Creator()).ExecuteCommandAsync();
                //if (isOk1 < 1)
                //{
                //    throw Oops.Oh(ErrorCode.COM1000);
                //}
                //else
                //{
                //    output.snum++;
                //}
            }
            catch (Exception ex)
            {
                item.exceptionMsg = ex.Message;
                output.failResult.Add(item);
                output.fnum++;
            }
        }
        if (output.snum == input.list.Count)
        {
            output.resultType = 1;
            // 关闭事务
            _db.CommitTran();
        }
        else
        {
            output.resultType = 0;
            // 回滚事务
            _db.RollbackTran();
        }
        return output;
    }

    /// <summary>
    /// 模板下载.
    /// </summary>
    /// <returns></returns>
    [HttpGet("TemplateDownload")]
    public async Task<dynamic> TemplateDownload()
    {
        string _fileName = "跳检规则模板.xlsx";
        var filePath = Path.Combine(FileVariable.TemplateFilePath, "inspectionrolemain_import_template.xlsx"); // 模板路径
        var addFilePath = Path.Combine(FileVariable.TemplateFilePath, _fileName); // 保存路径
        if (!(await _fileManager.ExistsFile(addFilePath)))
        {
            var stream = await _fileManager.GetFileStream(filePath);
            await _fileManager.UploadFileByType(stream, FileVariable.TemporaryFilePath, _fileName);
        }

        return new { name = _fileName, url = "/api/file/Download?encryption=" + DESCEncryption.Encrypt(_userManager.UserId + "|" + _fileName, "SHZY") };
    }

    /// <summary>
    /// 导入预览.
    /// </summary>
    /// <param name="fileName"></param>
    /// <returns></returns>
    [HttpGet("ImportPreview")]
    public async Task<dynamic> ImportPreview(string fileName)
    {
        try
        {
            var filePath = FileVariable.TemporaryFilePath;
            var savePath = Path.Combine(filePath, fileName);
            // 得到数据
            var sr = await _fileManager.GetFileStream(savePath);
            var excelData = ExcelImportHelper.ToDataTable(savePath, sr);
            foreach (var item in excelData.Columns)
            {
                excelData.Columns[item.ToString()].ColumnName = GetFileEncode(item.ToString());
            }
            // 删除文件
            await _fileManager.DeleteFile(savePath);
            // 返回结果
            return new { dataRow = excelData };
        }
        catch (Exception)
        {

            throw Oops.Oh(ErrorCode.D1801);
        }
    }
    /// <summary>
    /// 获取字段编码.
    /// </summary>
    /// <param name="filed"></param>
    /// <returns></returns>
    private string GetFileEncode(string filed)
    {
        switch (filed)
        {
            case "规则编码":
                return "code";
            case "规则描述":
                return "desc";
            case "有效开始时间":
                return "startDate";
            case "有效结束时间":
                return "endDate";
            case "有效标志":
                return "enabledMark";
            case "阶段":
                return "stage";
            case "阶段描述":
                return "stageDesc";
            case "条件":
                return "judeCondition";
            case "连续天数":
                return "continuityDay";
            case "合格数":
                return "inspLot";
            case "与批次关系":
                return "keyWord";
            case "新阶段":
                return "okStageNo";
            case "拒绝":
                return "rejectNun";
            case "NG新阶段":
                return "ngStageNo";
            case "初始阶段":
                return "isDefault";
            case "免检":
                return "isExempt";
            case "有效标志（明细）":
                return "enabledMark1";
            default:
                return string.Empty;
        }

    }
}